package com.tjn.thread;

/**
 * @author 陶镓妮
 * @version 1.0
 */
public class SellTicket {
    public static void main(String[] args) {
        SellTicket01 sellTicket01 = new SellTicket01();
        SellTicket01 sellTicket02 = new SellTicket01();
        SellTicket01 sellTicket03 = new SellTicket01();
        sellTicket01.start();
        sellTicket02.start();
        sellTicket03.start();

//        SellTicket02 sellTicket02 = new SellTicket02();
//        Thread thread01 = new Thread(sellTicket02);
//        Thread thread02 = new Thread(sellTicket02);
//        Thread thread03 = new Thread(sellTicket02);
//        thread01.start();
//        thread02.start();
//        thread03.start();

        //两种方式都会造成票重复出售或者超售
    }
}
//用Thread类来实现买票功能
class SellTicket01 extends Thread{
    private static int ticket = 100;//用静态的变量，就可以保证多个线程享用同一个 ticket
    @Override
    public void run() {
        while(true){
            System.out.println("窗口"+ Thread.currentThread().getName() + "卖出一张票,还有" + (--ticket) + "张票");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(ticket <= 0){
                System.out.println("票卖完了");
                break;
            }
        }
    }
}

//用Runnable接口来实现买票功能
class SellTicket02 implements Runnable{
    private int ticket = 100;//用Runnable接口实现，不需要static关键字，因为在创建每个线程时，引入的创建的对象是一样的，所以用的同一个ticket
    @Override
    public void run() {
        while(true){
            System.out.println("窗口"+ Thread.currentThread().getName() + "卖出一张票,还有" + (--ticket) + "张票");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(ticket <= 0){
                System.out.println("票卖完了");
                break;
            }
        }
    }
}